package com.deshan.websys.code.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deshan.websys.code.mapper.CustomerMapper;
import com.deshan.websys.code.model.Customers;
import com.deshan.websys.code.model.Visitors;
import com.deshan.websys.code.model.vo.CustomersVO;
import com.deshan.websys.code.model.vo.VisitLogVO;
import com.deshan.websys.code.service.ChatRecordService;
import com.deshan.websys.code.service.CustomersService;
import com.deshan.websys.code.service.VisitorsService;
import com.deshan.websys.code.utils.Constant;

import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class CustomersServiceImpl extends ServiceImpl<CustomerMapper, Customers> implements CustomersService {

	private final CustomerMapper customerMapper;

	private final VisitorsService visitorsService;

	private final ChatRecordService chatRecordService;

	@Override
	public List<CustomersVO> getCustomersListByLegalCode(String legalCode) {

		return customerMapper.getCustomersListByLegalCode(legalCode);
	}

	@Override
	public CustomersVO getServiceForLeastCustomer(String legalCode) {
		return Optional.ofNullable((customerMapper.getServiceForLeastCustomer(legalCode)).get(0))
				.orElseGet(() -> createServicerByLegalCode(legalCode));
	}

	@Override
	@Transactional
	public CustomersVO getCustomerServiceByCid(VisitLogVO visitLogVO) {
		CustomersVO customersVO = new CustomersVO();
		Customers customer = getById(visitLogVO.getCustomerId());

		if (Objects.nonNull(customer)) {
			Visitors friendship = getFriendship(customer.getId());
			if (Objects.nonNull(friendship)) {
				Customers servicer = getById(friendship.getServiceId());
				customersVO.setVisitorId(friendship.getId());
				customersVO.setNameCn(servicer.getNameCn());
				customersVO.setNickname(servicer.getNickname());
				customersVO.setUsername(servicer.getUsername());
				customersVO.setId(servicer.getId());
				customersVO.setChatRecordsList(
						chatRecordService.listChatRecords(visitLogVO.getCustomerId(), customersVO.getId()));
			} else {
				customersVO = getServiceForLeastCustomer(visitLogVO.getLegalCode());
				Visitors visitors = establishFriendship(visitLogVO, customersVO.getId());
				customersVO.setId(visitors.getId());
			}
			customersVO.setLegalCode(visitLogVO.getLegalCode());
			customersVO.setNameCnCustomer(customer.getNameCn());
			customersVO.setNicknameCustomer(customer.getNickname());
			customersVO.setUsernameCustomer(customer.getUsername());
			return customersVO;
		}

		log.info("getCustomerServiceByCid()---用户：{},不存在,创建新用户,选择好友最少的客服,设置好友关系," + "并返回法人：{}所属的所有客服信息",
				visitLogVO.getCustomerId(), visitLogVO.getLegalCode());

		customer = createCustomerByLegalCodeAndId(visitLogVO.getLegalCode(), visitLogVO.getCustomerId());

		customersVO = getServiceForLeastCustomer(visitLogVO.getLegalCode());
		Visitors visitors = establishFriendship(visitLogVO, customersVO.getId());
		
		customersVO.setVisitorId(visitors.getId());
		customersVO.setLegalCode(visitLogVO.getLegalCode());
		customersVO.setNameCnCustomer(customer.getNameCn());
		customersVO.setNicknameCustomer(customer.getNickname());
		customersVO.setUsernameCustomer(customer.getUsername());
		customersVO
				.setChatRecordsList(chatRecordService.listChatRecords(visitLogVO.getCustomerId(), customersVO.getId()));

		return customersVO;
	}

	/**
	 * 根据客户ID，获取已建立好友关系的客服
	 * 
	 * @param cid
	 * @return
	 */
	private Visitors getFriendship(String cid) {
		return visitorsService.getOne(Wrappers.lambdaQuery(Visitors.class).eq(Visitors::getCustomerId, cid));
	}

	/**
	 * 根据法人编码，创建新客服
	 * 
	 * @param legalCode
	 * @return
	 */
	private CustomersVO createServicerByLegalCode(String legalCode) {
		Customers customers = new Customers();
		customers.setMainCor(legalCode);
		customers.setNameCn(Constant.SERVICER_NICKNAME_PREFIXX + RandomUtil.randomInt(1, Constant.SERVICE_ROLE_TYPE));
		customers.setRoleType(2);
		customers.setNickname(customers.getNameCn());

		CustomersVO customersVO = new CustomersVO();
		BeanUtils.copyProperties(customers, customersVO);
		return customersVO;
	}

	private Visitors establishFriendship(VisitLogVO visitLogVO, String servicerId) {
		Visitors visitors = new Visitors();
		visitors.setServiceId(servicerId);
		visitors.setLegalCode(visitLogVO.getLegalCode());
		visitors.setCustomerId(visitLogVO.getCustomerId());
		visitors.setId(IdWorker.getId() + "");
		visitorsService.save(visitors);
		return visitors;
	}

	@Override
	public Customers createCustomerByLegalCodeAndId(String legalCode, String id) {
		Customers customer = new Customers();
		customer.setMainCor(legalCode);
		customer.setId(id);
		customer.setRoleType(Constant.CUSTOMER_ROLE_TYPE);
		customer.setNickname(Constant.VISIT_USER_NICKNAME_PREFIXX + RandomUtil.randomInt(1, Integer.MAX_VALUE));
		customerMapper.insert(customer);
		return customer;
	}

	@Override
	public Customers getUserByUsername(String username) {
		return getOne(Wrappers.lambdaQuery(Customers.class).eq(Customers::getUsername, username).eq(Customers::getRoleType, Constant.CUSTOMER_ROLE_TYPE));
	}
}
